package VIEW;

import CONF.ConexaoOracle;
import MODEL.LineUpModel;
import MODEL.PessoaModel;
import MODEL.RockInRio;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.JOptionPane;

public class AssociarIngressosView extends javax.swing.JFrame {

    private ArrayList<LineUpModel> lineUpArray;
    public static Object[][] data;
    private Integer totalSelecionados;
    
    public AssociarIngressosView(ArrayList<LineUpModel> lineUpArray, Integer totalSelecionados) {
        this.lineUpArray       = lineUpArray;
        this.totalSelecionados = totalSelecionados;
        //initComponents();
        povoaComponentes();
    }

    private AssociarIngressosView() {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    private void povoaComponentes() {
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        botaoAssociarIngressos = new javax.swing.JButton();
        botaoVoltar = new javax.swing.JButton();
        
        //pega os locais dos shows
        ArrayList<String> nomeDasColunas = new ArrayList<>();
        nomeDasColunas.add("LineUp");
        nomeDasColunas.add("CPF do Espectador");
        String[] columnNames = nomeDasColunas.toArray(new String[nomeDasColunas.size()]);

        //trecho de código para criar os dados a serem utilizados na tabela

        AssociarIngressosView.data = new Object[totalSelecionados][columnNames.length];

        int indexLine = 0;

        for (LineUpModel lineUp : lineUpArray) {
            for (int j = 0; j < lineUp.getSelecionados(); j++) {           
                for (int i = 0; i < columnNames.length; i++) {
                    if (i == 0) {
                         AssociarIngressosView.data[indexLine+j][i] = lineUp.calendarToDataString(lineUp.getData());
                    } else if (i == 1) {
                         AssociarIngressosView.data[indexLine+j][i] = new Integer(0);
                    }
                }
            }
            indexLine += lineUp.getSelecionados();
        }

        jTable1.setModel(new javax.swing.table.DefaultTableModel(AssociarIngressosView.data, columnNames) {

            Class[] types = new Class[]{
                java.lang.Object.class, java.lang.Integer.class
            };

            @Override
            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }

            @Override
            public void setValueAt(Object o, int i, int i1) {
                if(i1 == 0 || i1 == 2){
                     AssociarIngressosView.data[i][i1] = o;
                }
                super.setValueAt(o, i, i1);
            }
        });
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);
        
        
        jTable1.getModel().addTableModelListener(new TableModelListener() {

            public void tableChanged(TableModelEvent ev) {                
                Integer cpf   = (Integer) jTable1.getValueAt(ev.getLastRow(), ev.getColumn());
                String lineUp = (String) jTable1.getValueAt(ev.getLastRow(), ev.getColumn()-1);
                
                AssociarIngressosView.data[ev.getLastRow()][ev.getColumn()] = cpf;
                                
                if (cpf != 0) {
                    //System.out.println(cpf.toString());
                    PessoaModel pessoa = new PessoaModel(cpf);
                    try {
                        pessoa.verificaPessoaDB(ConexaoOracle.conexao, lineUp);
                    } catch (SQLException ex) {
                        //System.out.println(e.getMessage());
                    }

                    if (pessoa.pessoaExiste() != 1) {
                        AssociarIngressosView.data[ev.getLastRow()][ev.getColumn()] = 0;
                        CadastraPessoaView cadastraPessoa = new CadastraPessoaView(ev.getLastRow(), pessoa, lineUp);
                        cadastraPessoa.setLocationRelativeTo(null);
                        cadastraPessoa.setVisible(true);                
                    }
                }
            }
        });
        
        


        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        
        botaoAssociarIngressos.setText("Associar Ingressos");
        botaoAssociarIngressos.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoAssociarIngressosActionPerformed(evt);
            }
        });

        botaoVoltar.setText("Voltar");
        botaoVoltar.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoVoltarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(botaoVoltar, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(botaoAssociarIngressos)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoAssociarIngressos)
                    .addComponent(botaoVoltar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        botaoAssociarIngressos = new javax.swing.JButton();
        botaoVoltar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Rock In Rio - Ingressos");

        jScrollPane1.setPreferredSize(new java.awt.Dimension(324, 322));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "-", "-"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.Object.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTable1.setPreferredSize(new java.awt.Dimension(300, 215));
        jScrollPane1.setViewportView(jTable1);

        botaoAssociarIngressos.setText("Associar Ingressos");
        botaoAssociarIngressos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoAssociarIngressosActionPerformed(evt);
            }
        });

        botaoVoltar.setText("Voltar");
        botaoVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoVoltarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(botaoVoltar, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 78, Short.MAX_VALUE)
                        .addComponent(botaoAssociarIngressos)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoAssociarIngressos)
                    .addComponent(botaoVoltar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botaoVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoVoltarActionPerformed
        RockInRio rir = new RockInRio();
        ArrayList<LineUpModel> todasLineUps = new ArrayList<>();
        try {
            todasLineUps = rir.getLineUpsDB(ConexaoOracle.conexao);
        } catch (SQLException ex) {
            Logger.getLogger(AssociarIngressosView.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        DisponibilidadeView disponibilidadeView = null;
        disponibilidadeView = new DisponibilidadeView(todasLineUps);
        disponibilidadeView.setLocationRelativeTo(null); 
        disponibilidadeView.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_botaoVoltarActionPerformed

    private void botaoAssociarIngressosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoAssociarIngressosActionPerformed

        for(Object[] object : AssociarIngressosView.data) {           
            if ((int) object[1] == 0) {
                JOptionPane.showMessageDialog(null, "Você não pode prosseguir sem informa um CPF válido para " + object[0].toString() + ".");
                return;
                
            }
        }
        
        this.dispose();
        ConfirmacaoView ConfirmarCompra = new ConfirmacaoView(lineUpArray, totalSelecionados, AssociarIngressosView.data);
        ConfirmarCompra.setLocationRelativeTo(null);
        ConfirmarCompra.setVisible(true);
    }//GEN-LAST:event_botaoAssociarIngressosActionPerformed
    
    public static void main(String args[]) {

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (
                ClassNotFoundException |
                InstantiationException | 
                IllegalAccessException | 
                javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AssociarIngressosView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new AssociarIngressosView().setVisible(true);
            }
        });
        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoAssociarIngressos;
    private javax.swing.JButton botaoVoltar;
    private javax.swing.JScrollPane jScrollPane1;
    public static javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
